package com.dj.product.k2faas.controller.datasource;

import com.dj.product.k2faas.common.dto.IdResponse;
import com.dj.product.k2faas.dto.datasource.CreateDataSourceRequest;
import com.dj.product.k2faas.dto.datasource.DataSourceResponse;
import com.dj.product.k2faas.dto.datasource.UpdateDataSourceRequest;
import com.dj.product.k2faas.common.enums.DataStatus;
import com.dj.product.k2faas.service.datasource.DataSourceService;
import com.dj.product.k2faas.validator.datasource.DataSourceValidator;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

/**
 * Created by 丁建 on 2025/9/23 09:27
 *
 * @author 丁建
 */
@RestController
@RequestMapping({ "/data-sources/" })
public class DataSourceController {

    @Autowired
    private DataSourceValidator dataSourceValidator;

    @Autowired
    private DataSourceService dataSourceService;

    @PostMapping
    public IdResponse<Long> add(@RequestBody @Valid CreateDataSourceRequest dataSource) {
        dataSourceValidator.assertNameAvailable(dataSource.getName());

        this.dataSourceService.testDataSource(dataSource);
        var id = this.dataSourceService.add(dataSource);
        return new IdResponse<Long>().setId(id);
    }

    @PutMapping({ "/{id}/" })
    public void edit(@RequestBody @Valid UpdateDataSourceRequest dataSource, @PathVariable long id) {
        dataSourceValidator.assertNameAvailable(id, dataSource.getName());

        this.dataSourceService.testDataSource(dataSource);
        this.dataSourceService.edit(dataSource);
    }

    @GetMapping({ "/{id}/" })
    public DataSourceResponse findById(@PathVariable long id) {
        return this.dataSourceService.findById(id);
    }

    @GetMapping
    public Page<DataSourceResponse> findAll(@RequestParam(required = false) String keyword, Pageable pageable) {
        return this.dataSourceService.findAll(keyword, pageable);
    }

    @PostMapping({ "/{id}/actions/disable/" })
    public void disable(@PathVariable long id) {
        this.dataSourceService.changeStatus(id, DataStatus.DISABLED);
    }

    @PostMapping({ "/{id}/actions/enable/" })
    public void enable(@PathVariable long id) {
        this.dataSourceService.changeStatus(id, DataStatus.NORMAL);
    }

    /**
     * 设置为默认使用的数据库
     */
    @PostMapping({ "/{id}/actions/set-as-default/" })
    public void setAsDefault(@PathVariable long id) {
        this.dataSourceService.setAsDefault(id);
    }

    @PostMapping({ "/test-connection/" })
    public void testConnection(@RequestBody @Valid CreateDataSourceRequest dataSource) {
        this.dataSourceService.testDataSource(dataSource);
    }

}
